package com.example.myapplication

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResultListener

const val SCORE = "SCORE"
const val REQUEST_CODE_MODIFY = 1

class Person_information : Fragment() {

    private val prefsName = "person_prefs"
    private val avatarFileName = "avatar.png"

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.activity_person_information, container, false)
        val sharedPreferences = requireActivity().getSharedPreferences(prefsName, Context.MODE_PRIVATE)

        // 初始化默认值
        if (sharedPreferences.getString("name", null) == null) {
            savePersonData(
                sharedPreferences,
                name = getString(R.string.name),
                ID = getString(R.string.ID),
                phone = getString(R.string.phone),
                address = getString(R.string.address),
                gender = getString(R.string.sex),
                hobbies = getString(R.string.love)
            )
        }

        // 读取头像
        val avatarBytes = loadAvatar(requireContext())

        // 更新 UI
        updateUI(view, sharedPreferences, avatarBytes)

        // 修改信息按钮
        view.findViewById<Button>(R.id.button_modify).setOnClickListener {
            val intent = Intent(activity, SecondActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE_MODIFY)
        }

        // 监听游戏返回分数
        setFragmentResultListener("requestKey") { _, bundle ->
            val score = bundle.getString(SCORE)?.toIntOrNull() ?: 0
            Log.d("Person_information", "Score received: $score")

            // 获取历史最高分
            val highScore = sharedPreferences.getInt("highest_score", 0)

            // 比较更新历史最高分
            if (score > highScore) {
                sharedPreferences.edit().putInt("highest_score", score).apply()
            }

            // 更新 UI
            updateUI(view, sharedPreferences, avatarBytes)
        }

        return view
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_about -> {
                AlertDialog.Builder(requireContext())
                    .setTitle("关于")
                    .setMessage("这是一个卡牌游戏应用程序。\n版本: 2.0\n开发者: 小明")
                    .setPositiveButton("确定") { dialog, _ -> dialog.dismiss() }
                    .show()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode != Activity.RESULT_OK || data == null) return

        val sharedPreferences = requireActivity().getSharedPreferences(prefsName, Context.MODE_PRIVATE)

        when (requestCode) {
            REQUEST_CODE_MODIFY -> {
                val name = data.getStringExtra("name")
                val ID = data.getStringExtra("ID")
                val phone = data.getStringExtra("phone")
                val address = data.getStringExtra("address")
                val gender = data.getStringExtra("gender")
                val hobbies = data.getStringExtra("hobbies")
                val imageBytes = data.getByteArrayExtra("image")

                savePersonData(sharedPreferences, name, ID, phone, address, gender, hobbies)
                imageBytes?.let { saveAvatar(requireContext(), it) }
                view?.let { updateUI(it, sharedPreferences, imageBytes ?: loadAvatar(requireContext())) }
            }
        }
    }

    private fun savePersonData(
        prefs: android.content.SharedPreferences,
        name: String? = null,
        ID: String? = null,
        phone: String? = null,
        address: String? = null,
        gender: String? = null,
        hobbies: String? = null
    ) {
        prefs.edit().apply {
            name?.let { putString("name", it) }
            ID?.let { putString("ID", it) }
            phone?.let { putString("phone", it) }
            address?.let { putString("address", it) }
            gender?.let { putString("gender", it) }
            hobbies?.let { putString("hobbies", it) }
            apply()
        }
    }

    private fun saveAvatar(context: Context, imageBytes: ByteArray) {
        try {
            context.openFileOutput(avatarFileName, Context.MODE_PRIVATE).use { it.write(imageBytes) }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun loadAvatar(context: Context): ByteArray? {
        return try {
            context.openFileInput(avatarFileName).use { it.readBytes() }
        } catch (e: Exception) {
            null
        }
    }

    /** 更新 UI 显示个人信息和历史最高分 */
    private fun updateUI(view: View, prefs: android.content.SharedPreferences, imageBytes: ByteArray? = null) {
        val name = prefs.getString("name", "")
        val ID = prefs.getString("ID", "")
        val phone = prefs.getString("phone", "")
        val address = prefs.getString("address", "")
        val gender = prefs.getString("gender", "")
        val hobbies = prefs.getString("hobbies", "")

        // 历史最高分
        val highScore = prefs.getInt("highest_score", 0)
        val displayScore = if (highScore > 0) highScore.toString() else "无"

        view.findViewById<TextView>(R.id.textView3).text = "姓名: $name"
        view.findViewById<TextView>(R.id.textView5).text = "学号: $ID"
        view.findViewById<TextView>(R.id.textView8).text = "电话: $phone"
        view.findViewById<TextView>(R.id.textView9).text = "地址: $address"
        view.findViewById<TextView>(R.id.textView4).text = "性别: $gender"
        view.findViewById<TextView>(R.id.textView6).text = "爱好: $hobbies"
        view.findViewById<TextView>(R.id.textView2).text = "$name $ID"

        view.findViewById<TextView>(R.id.score).text = "最高分：$displayScore"

        imageBytes?.let {
            val bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
            view.findViewById<ImageView>(R.id.imageView).setImageBitmap(bitmap)
        }
    }

    companion object {
        fun newInstance() = Person_information()
    }
}
